package projects

import (
	"github.com/beego/beego/v2/client/orm"
	beego "github.com/beego/beego/v2/server/web"
	"strconv"
	"time"
	"xpms/app/models"
	"xpms/cores/utils"
)

type ProjectsDocs struct {
	Id         int64 `orm:"pk;column(docid);" json:"Id,string" `
	Projectid  int64 `json:"Projectid,string"`
	Userid     int64 `json:"Userid,string"`
	Title      string
	Sort       int
	Keyword    string
	Content    string
	Url        string
	Attachment string
	Created    int64
	Changed    int64
}

func (this *ProjectsDocs) TableName() string {
	return models.TableName("projects_doc")
}
func init() {
	orm.RegisterModel(new(ProjectsDocs))
}

func AddDocs(upd DocDTO) error {
	o := orm.NewOrm()
	doc := new(ProjectsDocs)
	doc.Id = upd.Id
	doc.Projectid = upd.Projectid
	doc.Userid = upd.Userid
	doc.Title = upd.Title
	doc.Keyword = upd.Keyword
	doc.Sort = upd.Sort
	doc.Content = upd.Content
	doc.Url = upd.Url
	doc.Created = time.Now().Unix()
	doc.Changed = time.Now().Unix()
	doc.Attachment = upd.Attachment
	_, err := o.Insert(doc)
	return err
}

func UpdateDocs(id int64, upd DocDTO) error {
	var doc ProjectsDocs
	o := orm.NewOrm()
	doc = ProjectsDocs{Projectid: id}
	doc.Id = upd.Id
	doc.Title = upd.Title
	doc.Keyword = upd.Keyword
	doc.Sort = upd.Sort
	doc.Content = upd.Content
	doc.Url = upd.Url
	doc.Changed = time.Now().Unix()
	if upd.Attachment != "" {
		doc.Attachment = upd.Attachment
		_, err := o.Update(&doc, "title", "keyword", "sort", "content", "url", "changed", "attachment")
		return err
	} else {
		_, err := o.Update(&doc, "title", "keyword", "sort", "content", "url", "changed")
		return err
	}
}

func GetProjectDocsTitle(id int64) string {
	var title string
	var doc ProjectsDocs
	o := orm.NewOrm()
	o.QueryTable(models.TableName("projects_doc")).Filter("docid", id).One(&doc, "title")
	title = doc.Title
	return title
}

func GetProjectDocs(id int64) (ProjectsDocs, error) {
	var doc ProjectsDocs
	var err error
	o := orm.NewOrm()
	doc = ProjectsDocs{Id: id}
	err = o.Read(&doc)

	if err == orm.ErrNoRows {
		return doc, nil
	}
	return doc, err
}

func ListDocsForForm(projectId int64, page, offset int) (ops []ProjectsDocs) {
	if page < 1 {
		page = 1
	}
	if offset < 1 {
		offset = 100
	}
	start := (page - 1) * offset
	var doc []ProjectsDocs
	o := orm.NewOrm()
	qs := o.QueryTable(models.TableName("projects_doc"))
	cond := orm.NewCondition()
	if projectId > 0 {
		cond = cond.And("projectid", projectId)
	}
	qs = qs.SetCond(cond)
	qs.Limit(offset, start).All(&doc)

	return doc
}

func DeleteDoc(ids string, userid int64) error {
	o := orm.NewOrm()
	_, err := o.Raw("DELETE FROM "+models.TableName("projects_doc")+" WHERE docid IN("+ids+") AND userid=?", userid).Exec()
	return err
}

func DocPageExec(condArr map[string]interface{}, page int, offset int) (ops []ProjectsDocs) {
	o := orm.NewOrm()
	o.Raw(docPageSql(condArr, 1, page, offset)).QueryRows(&ops)
	return ops
}

func DocPageCountExec(condArr map[string]interface{}, page int, offset int) int64 {
	o := orm.NewOrm()
	var Dto int64
	o.Raw(docPageSql(condArr, 0, page, offset)).QueryRow(&Dto)
	return Dto
}

/**
  组装sql
*/
func docPageSql(condArr map[string]interface{}, ifsCount, page int, offset int) (string, []interface{}) {
	var sql string
	if ifsCount == 0 {
		sql = sql + `SELECT count(1) FROM (`
	}
	sql = sql + `
	SELECT
	  pp.*
	FROM  pms_projects_doc pp where 1=1 `
	param := make([]interface{}, 0, 0)
	if !utils.IsEmpty(condArr["projectid"]) {
		sql = sql + ` and  pp.projectid=?`
		param = append(param, condArr["projectid"])
	}
	if !utils.IsEmpty(condArr["keyword"]) {
		sql = sql + ` and  pp.docid LIKE concat('%',?,'%')`
		param = append(param, condArr["keyword"])
	}
	if ifsCount == 0 {
		sql = sql + ` ) C`
	} else if ifsCount > 0 {
		if page < 1 {
			page = 1
		}
		if offset < 1 {
			offset, _ = beego.AppConfig.Int("pageoffset")
		}
		start := (page - 1) * offset
		startStr := strconv.Itoa(start)
		offsetStr := strconv.Itoa(offset)
		sql = sql + ` order by pp.docid  LIMIT ` + startStr + `,` + offsetStr
	}
	return sql, param
}
